class Solution {
public:
    int dx[4] = { 0,0,1,-1 };
    int dy[4] = { 1,-1,0,0 };
    bool exist(vector<vector<char>>& board, string word)
    {
        int n = board.size(), m = board[0].size();
        vector<vector<bool>> check(n, vector<bool>(m, false));

        function<bool(int, int, int)> dfs = [&](int i, int j, int index) {
            if (index == word.size()) return true;
            for (int a = 0; a < 4; a++)
            {
                int x = dx[a] + i, y = dy[a] + j;
                if (x >= 0 && x < n && y >= 0 && y < m && word[index] == board[x][y] && !check[x][y])
                {
                    check[x][y] = true;
                    if (dfs(x, y, index + 1)) return true;
                    check[x][y] = false;
                }
            }
            return false;
            };

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (board[i][j] == word[0])
                {
                    check[i][j] = true;
                    if (dfs(i, j, 1)) return true;
                    check[i][j] = false;
                }
            }
        }
        return false;
    }
};